# coding=utf-8
import logging

from django.utils.decorators import method_decorator
from django.views.decorators.http import require_POST
from django.views.generic import TemplateView

from common.feedback import db as db
from common.notification.handler import notify_feedback
from common.utils.api import token_required, mask_string
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ClientError
from common.utils.tz import utc_to_local_str

_LOGGER = logging.getLogger(__name__)


class FeedBackView(TemplateView):
    def get(self, req):
        query_dict = req.GET.dict()
        items, total_count = db.list_feedback(query_dict)
        resp_items = []
        for item in items:
            data = item.as_dict()
            if data['phone'] and data['nick_name']:
                if data['nick_name'] == data['phone'] or data['nick_name'] == data['phone'][2:]:
                    data['nick_name'] = mask_string(data['nick_name'])
            if not data['phone'] and data['nick_name']:
                if len(data['nick_name']) == 11 and data['nick_name'][0] in ['1', '8']:
                    data['nick_name'] = mask_string(data['nick_name'])
            for k in 'updated_at', 'created_at':
                data[k] = utc_to_local_str(data[k])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dict.get('$page', 1),
                'total_count': total_count, 'size': len(resp_items)}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(FeedBackView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
@token_required
def reply_feedback(req):
    user_id = req.POST.get('user_id')
    reply_content = req.POST.get('reply_content')
    feedback_id = req.POST.get('feedback_id')
    feedback_dict = db.get_feedback(feedback_id).as_dict()
    if not user_id:
        raise ClientError('user_id missing')
    notify = notify_feedback(user_id, reply_content, feedback_dict['content'],
                             utc_to_local_str(feedback_dict['created_at']))
    info = {'notification_id': (notify.as_dict()).get('id')}
    db.upsert_feedback(info, feedback_id)
    return {}
